<template>
  <div class="h-[37vh]">
    <CommonCard title="设备用户分布" contentId="zzt">
      <template #content>
        <div ref="chart" class="w-full h-[275px]"></div>
      </template>
    </CommonCard>
  </div>
</template>
<script lang="ts" setup>
import CommonCard from '@/components/CommonCard.vue'
import * as echarts from 'echarts'
import { markRaw, onMounted, onUnmounted, ref, watch } from 'vue'

import { selectDeviceTypeGroup } from '@/api/home'
import { deviceObj, timeNum } from '@/utils/commonFn'
import { useCommonStore } from '@/stores/common'
const chart = ref<HTMLDivElement | null>(null)
const myChart = ref()

const option = ref<echarts.EChartsOption>({
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value',
    splitLine: {
      //坐标轴在grid区域中的分割线
      show: true,
      lineStyle: {
        color: '#51586c',
        type: 'dashed'
      }
    }
  },
  grid: {
    left: 0,
    right: 0,
    bottom: 0,
    top: 30,
    containLabel: true //是否包含坐标值
  },
  tooltip: {
    trigger: 'axis'
  },
  series: [
    {
      data: [],
      type: 'bar',
      barWidth: 20,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
          { offset: 0, color: 'rgba(115,176,255,0.5)' }, // 起点颜色
          { offset: 1, color: ' #0071F2' } // 结束颜色
        ])
      }
    }
  ]
})
const timer = ref()
onMounted(() => {
  myChart.value = markRaw(echarts.init(chart.value))
  initEchart()
  timer.value = setInterval(() => {
    initEchart()
  }, timeNum)
})

onUnmounted(() => {
  clearInterval(timer.value)
})
const formData = ref({
  institutionId: sessionStorage.getItem('institutionId')
})
watch(
  () => useCommonStore().institutionId,
  (value) => {
    formData.value.institutionId = value
    initEchart()
  }
)
const initEchart = async () => {
  const res: any = await selectDeviceTypeGroup(formData.value)
  let xData: string[] = []
  let ydata: string[] = []
  res.data.forEach((item: any) => {
    xData.push(deviceObj[item.deviceType])
    ydata.push(item.count)
  })
  let obj: any = option.value
  obj.xAxis.data = xData as never
  obj.series[0].data = ydata as never
  myChart.value.setOption(option.value)
  window.onresize = function () {
    myChart.value.resize()
  }
}
</script>

<style scoped></style>
